﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using IVinPlugins;
using System.Reflection;


namespace VinCalculator
{
	public class PluginManager
	{
		private IVinPlugin[] ipi;
		private Form MDIParentForm { get; set; }
		private ToolStripMenuItem ToolsMenuItem { get; set; }

		public PluginManager(Form mdiparentform, ToolStripMenuItem toolsMenuItem)
		{
			MDIParentForm = mdiparentform;
			ToolsMenuItem = toolsMenuItem;
		}

		public void RegisterPlugin(IVinPlugin plugin)
		{
//            MenuItem mn = new MenuItem(plugin.PluginName, new EventHandler(NewLoad));
			ToolStripMenuItem mnu = new ToolStripMenuItem(plugin.PluginName, plugin.PluginIcon, new EventHandler(NewLoad));
			mnu.Tag = plugin;
			Console.WriteLine("Registered: " + plugin.PluginName);
			ToolsMenuItem.DropDownItems.Add(mnu);
		}

		private void NewLoad(object sender, System.EventArgs e)
		{
			ToolStripMenuItem mn = (ToolStripMenuItem)sender;
			IVinPlugin plugin = (IVinPlugin)mn.Tag;
			plugin.Show(MDIParentForm);
		}

		public string[] GetPluginFilesList()
		{
			string path = Application.StartupPath;
			string[] pluginFiles = Directory.GetFiles(path, "*.dll");
			return pluginFiles;
		}
		 

		public void InitializePlugins()
		{
			string[] m_plugins = GetPluginFilesList();
			ipi = new IVinPlugin[m_plugins.Length];

			for (int i = 0; i < m_plugins.Length; i++)
			{
				string args = m_plugins[i].Substring(
					m_plugins[i].LastIndexOf("\\") + 1,
					m_plugins[i].IndexOf(".dll") -
					m_plugins[i].LastIndexOf("\\") - 1);

				Type ObjType = null;
				//IPlugin ipi;
				// load the dll
				try
				{
					// load it
					Assembly ass = null;
					ass = Assembly.LoadFrom(m_plugins[i]);
					if (ass != null)
					{
						ObjType = ass.GetType(args+".Plugin");
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				} 
				try
				{
					// OK Lets create the object as we have the Report Type
					if (ObjType != null)
					{
						ipi[i] = (IVinPlugin)Activator.CreateInstance(ObjType);
						ipi[i].Host = (IPluginHost)MDIParentForm; 
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}

		}

	}
}
